<template>
  <a-space :size="22" direction="vertical">
    <page-form ref="formRefs" layout="vertical" :model="copyEnterpriseDetail">
      <template v-for="(child, index) in copyEnterpriseDetail.detail" :key="child.id">
        <a-card
          :style="{
            width: '800px',
            position: 'relative',
            marginBottom: '20px',
          }"
        >
          <span
            class="a-card__close"
            @click="() => delEnterpriseDetail(child, index)"
            v-if="status === 'edit' && child.wayType.ifDefault === 0"
          >
            <icon-close />
          </span>
          <div class="editable-item">
            <div class="editable-item-content">
              <page-form-row>
                <page-form-item :field="`detail.${index}.wayType.way`" label="结算方式" size="1/2" :rules="accountRule">
                  <sysdict-select
                    :disabled="status !== 'edit' || child.wayType.ifDefault !== 0"
                    v-model="child.wayType.way"
                    code="in_exp_account_way"
                    :disabledList="disabledList"
                    @change="onSysdictSelectChange"
                  />
                </page-form-item>
                <page-form-item :field="`detail.${index}.wayType.type`" label="收付款类型" size="1/2" :rules="bankRule">
                  <a-select
                    :disabled="status !== 'edit' || child.wayType.ifDefault !== 0"
                    v-model="child.wayType.type"
                    placeholder="请选择"
                  >
                    <a-option v-for="item in pageDirct.inExpTypeList" :key="item.value" :value="item.value" :label="item.label" />
                  </a-select>
                </page-form-item>
              </page-form-row>
            </div>
          </div>
          <div class="editable-item" v-if="child.account && child.account.length > 0">
            <div class="editable-item-content">
              <!-- 嘉联聚合支付 -->
              <div class="page-form-block" v-if="child.wayType.way == -1">
                <div class="contact-item" v-for="(item, index2) in child.account" :key="index2">
                  <page-form-row>
                    <page-form-item class="page-form-item-1" size="1/2" :field="`child.${index2}.account`" label="结算主体">
                      <a-input disabled v-model="item.bank" placeholder="请输入" :max-length="50" />
                    </page-form-item>
                  </page-form-row>
                </div>
              </div>
              <div class="page-form-block" v-else>
                <div class="contact-item" v-for="(item, index2) in child.account" :key="index2">
                  <page-form-row>
                    <page-form-item
                      class="page-form-item-1"
                      size="1/2"
                      :field="`child.${index2}.account`"
                      :label="index2 == 0 ? (child.wayType.way == -1 ? '收付款账号' : '结算账号') : ''"
                    >
                      <a-input
                        :disabled="status !== 'edit' || !child.wayType.way"
                        v-model="item.account"
                        placeholder="请输入"
                        :max-length="50"
                        allow-clear
                      />
                    </page-form-item>
                    <page-form-item
                      class="page-form-item-2"
                      size="1/2"
                      :field="`child.${index2}.bank`"
                      :label="index2 == 0 ? '开户行' : ''"
                    >
                      <a-input
                        :disabled="status !== 'edit' || !child.wayType.way"
                        v-model="item.bank"
                        placeholder="请输入"
                        :max-length="50"
                      />
                    </page-form-item>
                  </page-form-row>
                  <div class="flex operate-list">
                    <a-space :size="16">
                      <a-popconfirm
                        v-if="status === 'edit' && (child.account.length > 1 || child.cannotAdd)"
                        type="warning"
                        content="是否确认删除？"
                        @ok="delEpContactFn(child, index2)"
                      >
                        <a-button class="operate-btn del" type="text">
                          <template #icon>
                            <icon-minus-circle />
                          </template>
                          删除
                        </a-button>
                      </a-popconfirm>
                      <a-button
                        class="operate-btn new"
                        type="text"
                        @click="() => newEpContactFn(child)"
                        v-if="status === 'edit' && index2 == child.account.length - 1 && child.cannotAdd != true"
                      >
                        <template #icon>
                          <icon-plus-circle />
                        </template>
                        新增
                      </a-button>
                    </a-space>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </a-card>
      </template>
      <a-button type="primary" long v-if="status === 'edit'" @click="newEnterpriseDetail">
        <template #icon>
          <icon-plus />
        </template>
        增加
      </a-button>
      <br />
    </page-form>
  </a-space>
</template>

<script setup lang="ts">
  import { watch, reactive, ref } from 'vue'

  import SysdictSelect from '@/components/sysdict/sysdict-select.vue'
  import { cloneDeep } from 'lodash-es'
  import { usePageDict } from '@/hooks/useDict'
  import { FormInstance } from 'element-plus'

  interface Props {
    status: string
    enterpriseDetail: any
  }

  const pageDirct = usePageDict('randeaccountPageData')
  const formRefs = ref<FormInstance>()
  const accountRule = [{ required: true, message: '请选择结算方式' }]
  const bankRule = [{ required: true, message: '请选择收付款类型' }]
  const props = defineProps<Props>()
  const disabledList = ref<number[]>([])
  const copyEnterpriseDetail = reactive<{ detail: any }>({
    detail: [],
  })
  const defaultAccount = {
    id: '',
    account: '',
    bank: '',
  }

  const tmpChild = ref()

  const onSysdictSelectChange = () => {
    disabledList.value = []
    copyEnterpriseDetail.detail.forEach((item: any) => {
      disabledList.value.push(item.wayType.way)
    })
  }

  const delEnterpriseDetail = (child: any, index: number) => {
    copyEnterpriseDetail.detail.splice(index, 1)

    const id = disabledList.value.findIndex((item) => item === child.wayType.way!)
    id > -1 && disabledList.value.splice(id, 1)
  }

  const delEpContactFn = (child: any, index: number) => {
    child.account.splice(index, 1)
  }

  const newEpContactFn = (child: any) => {
    child.account.push({ ...defaultAccount })
  }

  const newEnterpriseDetail = () => {
    tmpChild.value = null
    copyEnterpriseDetail.detail.push({
      wayType: {
        id: '',
        ifDefault: 0,
      },
      account: [
        {
          id: '',
          account: '',
          bank: '',
        },
      ],
    })
  }

  const save = () => {
    return new Promise((resolve, reject) => {
      formRefs.value?.validate((valid) => {
        if (valid) {
          reject()
        } else {
          resolve(copyEnterpriseDetail.detail)
        }
      })
    })
  }

  defineExpose({
    save,
  })

  watch(
    () => [props.enterpriseDetail, props.status],
    ([val1, val2]) => {
      disabledList.value = []
      copyEnterpriseDetail.detail = cloneDeep(val1)
      if (val2 === 'edit') {
        copyEnterpriseDetail.detail.forEach((item: any) => {
          if ((!item.account || item.account.length === 0) && item.wayType.way != -2) {
            if (item.cannotAdd != true) {
              item.account = [{ ...defaultAccount }]
            }
          }
        })
        console.log('copyEnterpriseDetail', copyEnterpriseDetail.detail)
      }
      disabledList.value.push(...copyEnterpriseDetail.detail.map((item: any) => item.wayType.way!))
    },
    { immediate: true, deep: true }
  )
</script>

<style scoped lang="less">
  .page-form-item-1 {
    padding-right: 7px !important;
  }
  .page-form-item-2 {
    padding-left: 7px !important;
  }
  .a-card__close {
    position: absolute;
    top: 12px;
    right: 12px;
    width: 16px;
    height: 16px;
    cursor: pointer;
  }
  .page-form-block {
    background: rgba(247, 248, 250, 0.5);
    padding: 20px 172px 0 20px;
    // margin-bottom: 20px;

    .contact-item {
      position: relative;
      .operate-list {
        position: absolute;
        left: 100%;
        bottom: 20px;
        width: 154px;
        padding-left: 16px;
        .operate-btn {
          font-size: 14px;
          height: 32px;
          line-height: 32px;
          white-space: nowrap;
          outline: none;
          cursor: pointer;
          user-select: none;
          padding: 0 5px;
          &.del {
            color: #ea0000;
          }
          &.new {
            color: #165dff;
          }
        }
      }
    }
  }
</style>
